package com.sentiment.db;

import org.bson.Document;

import com.sentiment.obj.RalationMap;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class RalationMapDB {
	private MongoClient mongoClient;
	private MongoDatabase mongodb;
	private MongoCollection<Document> mongoCollection;

	public RalationMapDB() {

		mongoClient = new MongoClient();

		mongodb = mongoClient.getDatabase("detection");

		mongoCollection = mongodb.getCollection("rmCollection");
	}

	public void DBClose() {
		mongoClient.close();
	}

	/**
	 * @param data
	 *            待存入数据库的数据结构
	 */
	public void insertData(RalationMap data) {

		// 创建一个document并插入
		Document doc = new Document("srcId", data.getSrcId()).append("tarIdAll", data.getTarIdAll()).append("tarAmount",
				data.getTarAmount());

		mongoCollection.insertOne(doc);
	}

	public RalationMap findDataByKeyAndVal(String key, String val) {
		Document doc = mongoCollection.find(Filters.eq(key, val)).first();
		if (doc == null)
			return null;
		RalationMap rm = new RalationMap(doc);

		return rm;
	}

	public void cleanAll() {
		// 清理掉collection中原有的数据
		mongoCollection.drop();
	}
}
